/*
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-01-24 09:16:47
 * @LastEditTime: 2022-05-19 10:21:17
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
 */
import { login, getUserInfo } from '@/api/sys'
import md5 from 'md5'
import { setItem, getItem, removeAllItem } from '@/utils/storage'
import { TOKEN } from '@/constant'
import router, { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || '',
    userInfo: {}
  }),
  mutations: {
    setToken(state, value) {
      state.token = value
      setItem(TOKEN, value)
    },
    setUserInfo(state, value) {
      state.userInfo = value
    }
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({ username, password: md5(password) }).then((data) => {
          commit('setToken', data.token)
          resolve()
        }).catch((err) => {
          reject(err)
        })
      })
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
      const data = await getUserInfo()
      commit('setUserInfo', data)
      return data
    },
    // 退出
    logout({ commit }) {
      // 清空路由
      resetRouter()
      // 清空 Token
      commit('setToken', '')
      // 清空用户信息
      commit('setUserInfo', {})
      // 清空本地存储
      removeAllItem()
      // 返回登录页
      router.push('/logout')
    }
  }
}
